package com.itranswarp.learnjava.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itranswarp.learnjava.bean.SignInBean;
import com.itranswarp.learnjava.bean.User;
import com.itranswarp.learnjava.bean.PageResult;
import com.itranswarp.learnjava.bean.Permission;
import com.itranswarp.learnjava.bean.Page;

import com.itranswarp.learnjava.dao.UserDAO;
import com.itranswarp.learnjava.dao.PermissionDAO;

import com.itranswarp.learnjava.framework.ModelAndView;
import com.itranswarp.learnjava.framework.PostMapping;
import com.itranswarp.learnjava.utils.Response;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Objects;

public class PermissionController {
    private int pageSize = 10;
    public static void writeJson(HttpServletResponse response, Object obj) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_OK); // ✅ 明确设置 200
        PrintWriter pw = response.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        pw.write(mapper.writeValueAsString(obj));
        pw.flush();
    }

    public static boolean validateUser(HttpSession session){
        User user = (User) session.getAttribute("user");
        return user != null;
    }
    @PostMapping("/api/getAllPermissions")
    public ModelAndView doAllPermissions(Page pager, HttpServletResponse response, HttpSession session) throws IOException, SQLException {
        if(!validateUser(session)){
            writeJson(response, new Response<>(401, "未登录", null));
        } else {
            int offset = pager.page-1;
            PageResult<Permission> reuslt= PermissionDAO.getAllPermissions(Math.max(offset, 0), this.pageSize);
            writeJson(response, new Response<>(200, "", reuslt));
        }
        return null;
    }
}
